﻿using System;
using System.ComponentModel.Composition;
using Red.Controls.Shell;
using Red.EngineData.View;

namespace Red.Toolkit.AnimationViewer
{
    /// <summary>
    ///     This is how we make the editor a plug-in
    /// </summary>
    [Export( typeof( IEditorInfo ) )]
    public class EditorInfo : IEditorInfo
    {
        public string Name
        {
            get { return "Animation Viewer"; }
        }

        public Type WindowClass
        {
            get { return typeof( AnimationViewer ); }
        }

        public Type SettingsClass
        {
            get { return typeof( AnimationUserSettings ); }
        }
    }
    
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class AnimationViewer : RedEditorWindow
    {
        public AnimationViewer( IEditorHost host, EditorInstanceData instanceData, EditorSharedData sharedData )
            : base( host, instanceData, sharedData )
        {
            InitializeComponent();
            BackendInitialized += RedMainWindow_BackendInitialized;
        }

        private void RedMainWindow_BackendInitialized( object sender, EventArgs e )
        {
            _animationList.DataContext = InstanceData.RootEditorItem;
            _animationList.TempshitInitialize( InstanceData.RootEditorItem.Data );
        }

        private async void OnImportAnimation( object sender, EventArgs e )
        {
            var dialog = new Microsoft.Win32.OpenFileDialog
            {
                //FileName = Path.GetFileName( param.Value ),
                InitialDirectory = SharedData.DepotInfo.RootPath,
                Multiselect = false,
                Filter = @"All resources (*.re)|*.re",      // TODO: list from importers
                Title = @"Select source file"
            };

            if ( true.Equals( dialog.ShowDialog() ) )
            {
                try
                {
                    string filepath = dialog.FileName;
                    var succeed = await InstanceData.RootEditorItem.ExecuteAsync<bool>( "importAnimation", filepath );

                    if ( succeed.Value )
                    {
                        InstanceData.NotifyDispatcher.NotifyInformation( "Animation imported" );
                    }
                    else
                    {
                        InstanceData.NotifyDispatcher.NotifyError( "Failed to import animation" );
                    }
                }
                catch( ProtocolException ex )
                {
                    await RedMessageBox.ShowAsync( this, RedDialogType.Ok, ex.Message, "Error" );
                }

                _animationList.Refresh();
            }
        }

        private void OnImportFinished( bool succeeded, string additionalInfo )
        {
            // TODO: fill with code
        }
    }
}
